<script setup lang="ts">
import { useBoolean } from '@/hooks'
import { adminApi } from '@/service/api/bizhi'

interface Props {
  modalName?: string
}

const {
  modalName = '',
} = defineProps<Props>()

const emit = defineEmits<{
  open: []
  close: []
  refresh: []
}>()

const { bool: modalVisible, setTrue: showModal, setFalse: hiddenModal } = useBoolean(false)

const { bool: submitLoading, setTrue: startLoading, setFalse: endLoading } = useBoolean(false)

interface AdminFormData {
  id?: number
  username: string
  email: string
  phone: string
  real_name: string
  role: 'super_admin' | 'admin'
  password?: string
  confirmPassword?: string
  is_active: boolean
}

const formDefault: AdminFormData = {
  username: '',
  email: '',
  phone: '',
  real_name: '',
  role: 'admin',
  password: '',
  confirmPassword: '',
  is_active: true,
}
const formModel = ref<AdminFormData>({ ...formDefault })

type ModalType = 'add' | 'view' | 'edit'
const modalType = shallowRef<ModalType>('add')
const modalTitle = computed(() => {
  const titleMap: Record<ModalType, string> = {
    add: '添加',
    view: '查看',
    edit: '编辑',
  }
  return `${titleMap[modalType.value]}${modalName}`
})

async function openModal(type: ModalType = 'add', data: any) {
  emit('open')
  modalType.value = type
  showModal()

  const handlers = {
    async add() {
      formModel.value = { ...formDefault }
    },
    async view() {
      if (!data) return
      formModel.value = {
        ...data,
        password: '',
        confirmPassword: ''
      }
    },
    async edit() {
      if (!data) return
      formModel.value = {
        ...data,
        password: '',
        confirmPassword: ''
      }
    },
  }
  await handlers[type]()
}

function closeModal() {
  hiddenModal()
  endLoading()
  emit('close')
}

defineExpose({
  openModal,
})

const formRef = ref()
async function submitModal() {
  const handlers = {
    async add() {
      try {
        const { confirmPassword, ...submitData } = formModel.value
        const response = await adminApi.createAdmin(submitData)
        if (response.code === 200) {
          window.$message.success('管理员创建成功')
          emit('refresh')
          return true
        }
      } catch (error: any) {
        window.$message.error(error?.response?.data?.message || '创建失败')
        return false
      }
    },
    async edit() {
      try {
        const { confirmPassword, password, ...submitData } = formModel.value
        const response = await adminApi.editAdmin(formModel.value.id!, submitData)
        if (response.code === 200) {
          window.$message.success('管理员信息更新成功')
          emit('refresh')
          return true
        }
      } catch (error: any) {
        window.$message.error(error?.response?.data?.message || '更新失败')
        return false
      }
    },
    async view() {
      return true
    },
  }

  try {
    await formRef.value?.validate()
    startLoading()
    const success = await handlers[modalType.value]()
    if (success) {
      closeModal()
    }
  } catch (error) {
    // 验证失败
  } finally {
    endLoading()
  }
}

// 动态验证规则
const rules = computed(() => ({
  username: [
    {
      required: true,
      message: '请输入用户名',
      trigger: 'blur',
    },
    {
      min: 3,
      max: 50,
      message: '用户名长度必须在3-50个字符之间',
      trigger: 'blur',
    }
  ],
  email: [
    {
      required: modalType.value === 'add',
      message: '请输入邮箱',
      trigger: 'blur',
    },
    {
      type: 'email',
      message: '请输入正确的邮箱格式',
      trigger: 'blur',
    }
  ],
  phone: [
    {
      required: modalType.value === 'add',
      message: '请输入手机号',
      trigger: 'blur',
    },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: '请输入正确的手机号格式',
      trigger: 'blur',
    }
  ],
  real_name: [
    {
      required: false,
      trigger: 'blur',
    },
    {
      min: 1,
      max: 50,
      message: '真实姓名长度必须在1-50个字符之间',
      trigger: 'blur',
    }
  ],
  role: {
    required: true,
    message: '请选择角色',
    trigger: 'change',
  },
  password: [
    {
      required: modalType.value === 'add',
      message: '请输入密码',
      trigger: 'blur',
    },
    {
      min: 6,
      max: 50,
      message: '密码长度必须在6-50个字符之间',
      trigger: 'blur',
    }
  ],
  confirmPassword: [
    {
      required: modalType.value === 'add',
      message: '请确认密码',
      trigger: 'blur',
    },
    {
      validator: (rule: any, value: string) => {
        return value === formModel.value.password
      },
      message: '两次输入的密码不一致',
      trigger: 'blur',
    }
  ]
}))

// 角色选项
const roleOptions = [
  { label: '超级管理员', value: 'super_admin' },
  { label: '普通管理员', value: 'admin' }
]
</script>

<template>
  <n-modal
    v-model:show="modalVisible"
    :mask-closable="false"
    preset="card"
    :title="modalTitle"
    style="width: 600px;"
    :segmented="{
      content: true,
      action: true,
    }"
  >
    <n-form ref="formRef" :rules="rules" label-placement="left" :model="formModel" :label-width="100" :disabled="modalType === 'view'">
      <n-form-item label="用户名" path="username">
        <n-input v-model:value="formModel.username" placeholder="请输入用户名" />
      </n-form-item>

      <n-form-item label="真实姓名" path="real_name">
        <n-input v-model:value="formModel.real_name" placeholder="请输入真实姓名" />
      </n-form-item>

      <n-form-item label="邮箱" path="email">
        <n-input v-model:value="formModel.email" placeholder="请输入邮箱" />
      </n-form-item>

      <n-form-item label="手机号" path="phone">
        <n-input v-model:value="formModel.phone" placeholder="请输入手机号" />
      </n-form-item>

      <n-form-item v-if="modalType === 'add'" label="密码" path="password">
        <n-input v-model:value="formModel.password" type="password" placeholder="请输入密码" show-password-on="click" />
      </n-form-item>

      <n-form-item v-if="modalType === 'add'" label="确认密码" path="confirmPassword">
        <n-input v-model:value="formModel.confirmPassword" type="password" placeholder="请再次输入密码" show-password-on="click" />
      </n-form-item>

      <n-form-item label="角色" path="role">
        <n-select v-model:value="formModel.role" :options="roleOptions" placeholder="请选择角色" />
      </n-form-item>

      <n-form-item label="状态" path="is_active">
        <n-radio-group v-model:value="formModel.is_active">
          <n-space>
            <n-radio :value="true">
              启用
            </n-radio>
            <n-radio :value="false">
              禁用
            </n-radio>
          </n-space>
        </n-radio-group>
      </n-form-item>
    </n-form>
    <template #action>
      <n-space justify="center">
        <n-button @click="closeModal">
          取消
        </n-button>
        <n-button type="primary" :loading="submitLoading" @click="submitModal">
          提交
        </n-button>
      </n-space>
    </template>
  </n-modal>
</template>
